package com.example.sihookuiklydemo.base

import com.example.sihookuiklydemo.theme.ThemeManager
import com.tencent.kuikly.core.coroutines.GlobalScope
import com.tencent.kuikly.core.coroutines.launch
import com.tencent.kuikly.core.datetime.DateTime
import com.tencent.kuikly.core.log.KLog
import com.tencent.kuikly.core.manager.PagerManager
import com.tencent.kuikly.core.module.Module
import com.tencent.kuikly.core.module.RouterModule
import com.tencent.kuikly.core.module.SharedPreferencesModule
import com.tencent.kuikly.core.module.toKotlinObject
import com.tencent.kuikly.core.nvi.serialization.json.JSONObject
import com.tencent.kuikly.core.pager.Pager
import com.tencent.kuikly.core.reactive.handler.*
import com.tencent.kuikly.core.views.Date


internal abstract class BasePager : Pager() {
    private var nightModel: Boolean? by observable(null)
    var theme by observable(ThemeManager.getTheme())
    var currentLanguage: String = "zhCn"
    var titleName: String? = null

    override fun createExternalModules(): Map<String, Module>? {
        val externalModules = hashMapOf<String, Module>()
        externalModules[BridgeModule.MODULE_NAME] = BridgeModule()
        return externalModules
    }

    override fun created() {
        super.created()
        isNightMode()

        val colorTheme = if (isNightMode()) "dark" else "light"
        val assetTheme =
            getPager().acquireModule<SharedPreferencesModule>(SharedPreferencesModule.MODULE_NAME)
                .getString("assetTheme").takeUnless { it.isEmpty() } ?: "default"
        val typoTheme =
            getPager().acquireModule<SharedPreferencesModule>(SharedPreferencesModule.MODULE_NAME)
                .getString("typoTheme").takeUnless { it.isEmpty() } ?: "default"

        ThemeManager.changeColorScheme(colorTheme)
        ThemeManager.changeAssetScheme(assetTheme)
        ThemeManager.changeTypoScheme(typoTheme)

        theme = ThemeManager.getTheme()
        var appLanguage = pageData.params.optString(LANGUAGE_NAME)
        if (appLanguage.isNotEmpty()) {
            currentLanguage = appLanguage
        }

        titleName = pageData.params.optString(TITLE_NAME)

        initLanguage()


    }

    override fun themeDidChanged(data: JSONObject) {
        super.themeDidChanged(data)
        KLog.i("BasePager", "themeDidChanged: ")
        nightModel = data.optBoolean(IS_NIGHT_MODE_KEY)
    }

    // 是否为夜间模式
    override fun isNightMode(): Boolean {
        if (nightModel == null) {
            nightModel = pageData.params.optBoolean(IS_NIGHT_MODE_KEY)
        }
        return nightModel!!
    }

    // 不开启调试UI模式
    override fun debugUIInspector(): Boolean {
        return false
    }


    companion object {
        const val IS_NIGHT_MODE_KEY = "isNightMode"
        const val LANGUAGE_NAME = "LANGUAGE_NAME"
        const val TITLE_NAME = "TITLE_NAME"
        const val LANGUAGE_FILE = "LANGUAGE_FILE"
        const val LANGUAGE_VERSION = "LANGUAGE_VERSION"
        var curLanguageBean: JSONObject? by observable(JSONObject())
        var lastLanguage: String? = null
    }

    fun getLanguage(key: String, defalutValue: String): String {
        var transText = curLanguageBean?.optString(key)
        return if (transText?.isNullOrEmpty() == true) defalutValue else transText!!
        // return if (languageValue.isNullOrEmpty()) defalutValue else languageValue
    }

    fun getFormatLanguage(key: String, formatValue: String): String? {
        var showText: String? = null
        getLanguage(key, "")?.let {
            showText = it.replace("{$}", formatValue)
        }
        return showText
    }

    fun initLanguage() {


        lastLanguage?.let {
            if (lastLanguage == currentLanguage) return
        }
        lastLanguage = currentLanguage
        KLog.i("initCurLanguageList", "startFile")
        var languageFile =
            acquireModule<SharedPreferencesModule>(SharedPreferencesModule.MODULE_NAME)
                .getObject(LANGUAGE_FILE)


        if (languageFile == null) {
            val bridgeModule =
                PagerManager.getCurrentPager().getModule<BridgeModule>(BridgeModule.MODULE_NAME)
            bridgeModule?.readAssetFile("common/language/multi_lang_config_2.1.383.json") { json ->
                KLog.i("initCurLanguageList", "jsonRead")
                var languageBean = json?.optJSONObject("result")
                var multiLangList = languageBean?.optJSONObject("multiLangList")
                acquireModule<SharedPreferencesModule>(SharedPreferencesModule.MODULE_NAME).setObject(
                    LANGUAGE_FILE,
                    languageBean
                )
                multiLangList?.let {
                    initCurLanguageList(it)
                }
                KLog.i("initCurLanguageList", "EndFIle")
                //  KLog.i("多语言 hashMapLanguage", "${jsonObject}")
            }

        } else {

            var multiLangList = languageFile?.optJSONObject("multiLangList")
            multiLangList?.let {
                initCurLanguageList(it)
            }
        }


        //GlobalScope.launch(Dispatchers.IO) {
        //initLanguageFile(languageFile)
        // }
        //


    }

    fun initLanguageFile(languageFile: JSONObject?) {

        val bridgeModule =
            PagerManager.getCurrentPager().getModule<BridgeModule>(BridgeModule.MODULE_NAME)
        bridgeModule?.readAssetFile("common/language/multi_lang_config_2.1.382.json") { json ->
            var languageBean = json?.optJSONObject("result")
            var multiLangList = languageBean?.optJSONObject("multiLangList")
            var version = languageBean?.optString("version")
            KLog.i("TAG", "initLanguageFile: $version ")
            if (languageFile == null) {
                saveLanguageInfo(languageBean, version, multiLangList)
            } else {
                var curVersion =
                    acquireModule<SharedPreferencesModule>(SharedPreferencesModule.MODULE_NAME)?.getString(
                        LANGUAGE_VERSION
                    )
                if (curVersion != version) {
                    saveLanguageInfo(languageBean, version, multiLangList)
                }
                KLog.i("TAG", "initLanguageFile: $version $curVersion")
            }


            //  KLog.i("多语言 hashMapLanguage", "${jsonObject}")
        }

    }

    fun saveLanguageInfo(languageBean: JSONObject?, version: String?, multiLangList: JSONObject?) {
        acquireModule<SharedPreferencesModule>(SharedPreferencesModule.MODULE_NAME).setObject(
            LANGUAGE_FILE,
            languageBean
        )
        version?.let {
            acquireModule<SharedPreferencesModule>(SharedPreferencesModule.MODULE_NAME)?.setString(
                LANGUAGE_VERSION, version
            )
        }
        multiLangList?.let {
            initCurLanguageList(it)
        }
    }

    fun initCurLanguageList(multiLangList: JSONObject) {

        var curLanguageList = multiLangList?.optJSONArray(currentLanguage)
        var data = JSONObject()
        KLog.i("initCurLanguageList", "start")
        curLanguageList?.let {
            for (i in 0 until it.length()) {
                it.optJSONObject(i)?.let { itemJson ->
                    data?.put(itemJson.optString("key"), itemJson.optString("text"))
                }
            }
        }
        KLog.i("initCurLanguageList", "end")
        curLanguageBean = data
    }

    fun openNameWithTitle(pageName: String, title: String) {
        var params = pagerData.params
        params.put(TITLE_NAME, title)
        acquireModule<RouterModule>(RouterModule.MODULE_NAME)
            .openPage(pageName, params)
    }
}